//路由鉴权
import router from "@/routers";
//进入进度条组件
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import settings from "./settings";
//进入用户仓库
import pinia from "./store";
import useUserStore from "@/store/modules/user";
let userStore = useUserStore(pinia);
//全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  document.title = `${settings.title}-${to.meta.title}`;
  NProgress.start();
  //获取token，判断用户是否登录
  let token = userStore.token;
  let username = userStore.username;
  if (token) {
    //用户已经登录
    if (to.path == "/login") {
      //用户已经登录，不能进入登录页面
      next({ path: "/" });
    } else {
      //用户已经登录，可以进入其他页面
      //有用户信息
      if (username) {
        next();
      } else {
        //无用户信息，获取用户信息
        try {
          await userStore.userInfo();
          next();
        } catch (error) {
          //token过期
          //手动修改用户信息
          await userStore.userLogout();
          next({ path: "/login" });
        }
      }
    }
  } else {
    //用户未登录
    if (to.path == "/login") {
      //用户未登录，可以进入登录页面
      next();
    } else {
      next({ path: "/login" });
    }
  }
});

//全局后置守卫
router.afterEach((to: any, from: any) => {
  NProgress.done();
});
